import logger from "@renderer/config/logger";
import type { UpdaterStatus } from "@shared/types/version-updater";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

const { updaterService } = window.service;
const { ipcRenderer } = window.electron;

enum IpcRendererEvent {
  UPDATER_CHECK_STATUS = "updater:check-status",
}

export function useVersionUpdate() {
  const { t } = useTranslation("translation", {
    keyPrefix: "settings.general-settings.version-update",
  });

  const [status, setStatus] = useState<UpdaterStatus>("idle");
  const [progress, setProgress] = useState<number>(0);

  const handleChange = async (checked: boolean): Promise<void> => {
    await updaterService.setAutoUpdate(checked);
  };

  const handleActions = async (): Promise<void> => {
    switch (status) {
      case "idle":
      case "not-available":
      case "error":
        await handleCheckForUpdates();
        break;
      case "available":
        await updaterService.update();
        break;
      case "downloaded":
        await updaterService.install();
        break;

      case "downloading":
      case "checking":
        break;
      default:
        break;
    }
  };

  const handleCheckForUpdates = async (): Promise<void> => {
    setStatus("checking");

    try {
      await updaterService.checkForUpdates();
    } catch (error) {
      logger.error("Failed to check for updates:", { error });
      toast.error(t("check-failed"));
      setStatus("idle");
    }
  };

  const handleCheckStatus = useCallback(
    (
      _event: Electron.IpcRendererEvent,
      data: { status: UpdaterStatus; version?: string; precent?: number },
    ) => {
      setStatus(data.status);

      logger.info("handleCheckStatus", { data });

      switch (data.status) {
        case "available":
          toast.success(`${t("update-available")}: ${data.version}`);
          break;
        case "not-available":
          toast.success(`${t("no-update-available")}: ${data.version}`);
          break;
        case "downloading":
          setProgress(data.precent ?? 0);
          break;
        case "downloaded":
          toast.success(t("update-downloaded"));
          break;
        case "error":
          toast.error(t("check-failed"));
          break;

        case "idle":
        case "checking":
          break;
        default:
          break;
      }
    },
    [t],
  );

  useEffect(() => {
    const checkUpdate = async () => {
      const status = await updaterService.getStatus();
      logger.info("checkUpdate", { status });
      setStatus(status);
    };

    checkUpdate();
  }, []);

  useEffect(() => {
    ipcRenderer.on(IpcRendererEvent.UPDATER_CHECK_STATUS, handleCheckStatus);

    return () => {
      ipcRenderer.removeAllListeners(IpcRendererEvent.UPDATER_CHECK_STATUS);
    };
  }, [handleCheckStatus]);

  return {
    status,
    progress,
    handleChange,
    handleActions,
  };
}
